package com.k8sops.backend.service.impl;

import com.k8sops.backend.common.BusinessException;
import com.k8sops.backend.entity.Role;
import com.k8sops.backend.entity.RoleMenuRelation;
import com.k8sops.backend.entity.RoleUserRelation;
import com.k8sops.backend.mapper.RoleMapper;
import com.k8sops.backend.mapper.RoleMenuRelationMapper;
import com.k8sops.backend.mapper.RoleUserRelationMapper;
import com.k8sops.backend.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色服务实现类
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuRelationMapper roleMenuRelationMapper;

    @Autowired
    private RoleUserRelationMapper roleUserRelationMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Role createRole(Role role) {
        // 检查角色代码是否已存在
        Role existingRole = roleMapper.selectByRoleCode(role.getRoleCode());
        if (existingRole != null) {
            throw new BusinessException("角色代码已存在");
        }
        
        // 设置为可操作角色
        role.setIsOperation(true);
        
        // 插入角色记录
        roleMapper.insert(role);
        return role;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Role updateRole(Role role) {
        // 检查角色是否存在
        Role existingRole = roleMapper.selectById(role.getId());
        if (existingRole == null) {
            throw new BusinessException("角色不存在");
        }
        
        // 检查角色是否可操作
        if (!existingRole.getIsOperation()) {
            throw new BusinessException("该角色不可修改");
        }
        
        // 更新角色记录
        roleMapper.update(role);
        return roleMapper.selectById(role.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRole(Long roleId) {
        // 检查角色是否存在
        Role existingRole = roleMapper.selectById(roleId);
        if (existingRole == null) {
            throw new BusinessException("角色不存在");
        }
        
        // 检查角色是否可操作
        if (!existingRole.getIsOperation()) {
            throw new BusinessException("该角色不可删除");
        }
        
        // 删除角色相关的菜单关联
        roleMenuRelationMapper.deleteByRoleId(roleId);
        
        // 删除角色相关的用户关联
        roleUserRelationMapper.deleteByRoleId(roleId);
        
        // 删除角色记录
        return roleMapper.deleteById(roleId) > 0;
    }

    @Override
    public Role getRoleById(Long roleId) {
        return roleMapper.selectById(roleId);
    }

    @Override
    public Role getRoleByCode(String roleCode) {
        return roleMapper.selectByRoleCode(roleCode);
    }

    @Override
    public List<Role> getAllRoles() {
        return roleMapper.selectAll();
    }

    @Override
    public List<Role> getOperationRoles() {
        return roleMapper.selectOperationRoles();
    }

    @Override
    public List<Role> getUserRoles(Long userId) {
        return roleMapper.selectRolesByUserId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignMenusToRole(Long roleId, List<Long> menuIds) {
        // 检查角色是否存在
        Role existingRole = roleMapper.selectById(roleId);
        if (existingRole == null) {
            throw new BusinessException("角色不存在");
        }
        
        // 删除原有的角色菜单关联
        roleMenuRelationMapper.deleteByRoleId(roleId);
        
        // 如果菜单ID列表为空，则只是清空关联
        if (menuIds == null || menuIds.isEmpty()) {
            return true;
        }
        
        // 创建新的角色菜单关联
        List<RoleMenuRelation> relations = new ArrayList<>();
        for (Long menuId : menuIds) {
            RoleMenuRelation relation = new RoleMenuRelation();
            relation.setRoleId(roleId);
            relation.setMenuId(menuId);
            relations.add(relation);
        }
        
        return roleMenuRelationMapper.batchInsert(relations) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignRolesToUser(Long userId, List<Long> roleIds) {
        // 删除原有的用户角色关联
        roleUserRelationMapper.deleteByUserId(userId);
        
        // 如果角色ID列表为空，则只是清空关联
        if (roleIds == null || roleIds.isEmpty()) {
            return true;
        }
        
        // 创建新的用户角色关联
        List<RoleUserRelation> relations = new ArrayList<>();
        for (Long roleId : roleIds) {
            // 检查角色是否存在
            Role existingRole = roleMapper.selectById(roleId);
            if (existingRole == null) {
                throw new BusinessException("角色不存在，ID: " + roleId);
            }
            
            RoleUserRelation relation = new RoleUserRelation();
            relation.setUserId(userId);
            relation.setRoleId(roleId);
            relations.add(relation);
        }
        
        return roleUserRelationMapper.batchInsert(relations) > 0;
    }
}
